package com.spring.cloud.service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.spring.cloud.entity.User;
import com.spring.cloud.enums.ExceptionEnum;
import com.spring.cloud.exception.GlobalException;
import com.spring.cloud.mapper.UserMapper;
import com.spring.cloud.utils.CodecUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class UserService {

    @Autowired
    private UserMapper userMapper;

    private static final String KEY_PREFIX = "cloud:verify:code:";

    public User findUserById(Integer userId){
        User user = userMapper.selectByPrimaryKey(userId);
        if (null == user){
            throw new GlobalException(ExceptionEnum.USER_NOT_FOUND);
        }
        return user;
    }

    public PageInfo<User> getUserList(Integer pageNum, Integer pageSize) {

        PageHelper.startPage(pageNum,pageSize);

        List<User> users = userMapper.selectAll();

        PageInfo pageInfo = new PageInfo(users);

        return pageInfo;
    }


    public User queryUser(String username, String password) {
        User record = new User();
        record.setUsername(username);

        //首先根据用户名查询用户
        User user = userMapper.selectOne(record);

        if (user == null) {
            throw new GlobalException(ExceptionEnum.USER_NOT_EXIST);
        }

        //检验密码是否正确
        if (!StringUtils.equals(CodecUtils.md5Hex(password, user.getSalt()), user.getPassword())) {
            //密码不正确
            throw new GlobalException(ExceptionEnum.PASSWORD_NOT_MATCHING);
        }

        return user;
    }


    public void register(User user) {

        user.setId(null);
        user.setCreated(LocalDateTime.now());
        String key = KEY_PREFIX + user.getPhone();

        //生成盐
        String salt = CodecUtils.generateSalt();
        user.setSalt(salt);

        //生成密码
        String md5Pwd = CodecUtils.md5Hex(user.getPassword(), user.getSalt());

        user.setPassword(md5Pwd);

        //保存到数据库
        int count = userMapper.insert(user);

        if (count != 1) {
            throw new GlobalException(ExceptionEnum.INVALID_PARAM);
        }

    }

    public User getUser(Integer id) {
        User user = userMapper.selectByPrimaryKey(id);
        return user;
    }
}
